import { createClient } from 'redis'

const redisConnect = {
  socket: { host: process.env.REDIS_HOST, port: Number(process.env.REDIS_PORT) },
  password: process.env.REDIS_PASSWORD,
  database: 1,
}

const localCacheConnect = {
  socket: { host: process.env.REDIS_CACHE_HOST, port: Number(process.env.REDIS_CACHE_PORT) },
  password: process.env.REDIS_CACHE_PASSWORD,
  database: 0,
}

let redisSub
let redisPub
let redisCache

export const getRedis = async () => {
  if (isNilOrEmpty(redisSub)) {
    redisSub = createClient(redisConnect)
    redisSub.on('error', (err) => console.log('Redis Client Error', err))
    await redisSub.connect()
  }
  return redisSub
}

export const getRedisPub = async () => {
  if (isNilOrEmpty(redisPub)) {
    redisPub = createClient(redisConnect)
    redisPub.on('error', (err) => console.log('Redis Client Error', err))
    await redisPub.connect()
  }
  return redisPub
}

export const getRedisCache = async () => {
  if (isNilOrEmpty(redisCache)) {
    redisCache = createClient(localCacheConnect)
    redisCache.on('error', (err) => console.log('Redis Client Error', err))
    await redisCache.connect()
  }
  return redisCache
}
